package com.jsbj.tools;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.*;
import java.util.*;

public class Util
{
  public static boolean checkNull(Object obj)
  {
    if (obj == null)
      return true;
    if (((obj instanceof String)) && ("".equals(obj)))
      return true;
    if (((obj instanceof Number)) && (((Number)obj).doubleValue() == 0.0D))
      return true;
    if (((obj instanceof Boolean)) && (!((Boolean)obj).booleanValue()))
      return true;
    if (((obj instanceof Collection)) && (((Collection)obj).isEmpty()))
      return true;
    if (((obj instanceof Map)) && (((Map)obj).isEmpty()))
      return true;
    if (((obj instanceof Object[])) && (((Object[])obj).length == 0)) {
      return true;
    }
    return false;
  }

  public static String fmtDateRemoveSymbol(String dateString)
  {
    String fmtdateString = dateString.replaceAll("-", "").replaceAll("/", "");
    return fmtdateString;
  }

  public static String transdateMY(String dateString)
  {
    String result = "";
    if ((dateString.contains("/")) || (dateString.contains("-"))) {
      result = dateString.substring(3, dateString.length()) + dateString.substring(0, 2);

      return result;
    }
    return dateString;
  }

  public static String transdateDMY(String dateString)
  {
    String result = "";
    if ((dateString.contains("/")) || (dateString.contains("-"))) {
      result = dateString.substring(6, dateString.length()) + dateString.substring(3, 5) + dateString.substring(0, 2);

      return result;
    }
    return dateString;
  }

  public static String getDateNdaysBefore(String dateString, int beforeday)
  {
    Calendar c = Calendar.getInstance();
    Date date = null;
    try {
      date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    c.setTime(date);
    int day = c.get(5);
    c.set(5, day - beforeday);
    String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
    return dayBefore;
  }

  public static String getCurrentDateYMDHMS()
  {
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    String result = df.format(new Date());
    return result;
  }

  public static Date stringDatetoDate(String dateString)
  {
    Calendar c = Calendar.getInstance();
    if ((dateString.contains("/")) || (dateString.contains("-"))) {
      dateString = dateString.replaceAll("-", "").replaceAll("/", "").replaceAll(" ", "").replaceAll(":", "");
    }
    int year = Integer.valueOf(dateString.substring(0, 4)).intValue();
    int month = Integer.valueOf(dateString.substring(4, 6)).intValue();
    int day = Integer.valueOf(dateString.substring(6, 8)).intValue();
    int hour = Integer.valueOf(dateString.substring(8, 10)).intValue();
    int min = Integer.valueOf(dateString.substring(10, 12)).intValue();
    c.set(year, month, day, hour, min);
    return c.getTime();
  }

  public static String getCurrentDateYMD()
  {
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String result = df.format(new Date());
    return result;
  }

  public static Double toround(Double d)
  {
    BigDecimal b = new BigDecimal(d.doubleValue());
    d = Double.valueOf(b.setScale(2, 4).doubleValue());
    return d;
  }

  public static String encodeFilename(String filename, HttpServletRequest request)
  {
    String agent = request.getHeader("USER-AGENT");
    try {
      if ((agent != null) && (-1 != agent.indexOf("MSIE"))) {
        String newFileName = URLEncoder.encode(filename, "UTF-8");
        newFileName = StringUtils.replace(newFileName, "+", "%20");
        if (newFileName.length() > 150)
          newFileName = new String(filename.getBytes("GB2312"), "ISO8859-1");
        return StringUtils.replace(newFileName, " ", "%20");
      }

      if ((agent != null) && (-1 != agent.indexOf("Mozilla")))
      {
        return filename;
      }return filename; } catch (Exception ex) {
    }
    return filename;
  }

  public static Double checkDouble(Double data)
  {
    Double rtn = Double.valueOf(0.0D);
    if (!checkNull(data)) {
      rtn = data;
    }
    return rtn;
  }

  public static String qianfenwei(Double doub)
  {
    DecimalFormat decimalFormat = new DecimalFormat("#,##0.##;(#)");
    return decimalFormat.format(doub);
  }

  public static List<String> stringToList(String dataString)
  {
    List rtnList = new ArrayList();
    if (dataString != null) {
      for (String part : dataString.split(",")) {
        if (!"".equals(part)) {
          rtnList.add(part);
        }
      }
    }
    return rtnList;
  }

  public static String string_unique(String phoneNumbers, String split)
  {
    String[] str = phoneNumbers.split(split);
    List list = new ArrayList();
    for (int i = 0; i < str.length; i++) {
      if (!list.contains(str[i]) && StringUtils.isNotEmpty(str[i])) {	//防止号码为空
        list.add(str[i]);
      }
    }

    String rtnString = split;
    if (list.size() > 0) {
      for (int j = 0; j < list.size(); j++) {
        if (!checkNull(list.get(j))) {
          rtnString = rtnString + (String)list.get(j) + split;
        }
      }
    }
    return rtnString;
  }
  
  /**
	 * @author wangjing
	 * 对以‘，’分隔的字符串去重
	 * @return
	 */
	public static String string_unique_new(String phoneNumbers,String split) {
		String[] str = phoneNumbers.split(split);
		List<String> list = new ArrayList<String>();  
      for (int i=0; i<str.length; i++) {  
           if(!list.contains(str[i]) && StringUtils.isNotEmpty(str[i])) {  
               list.add(str[i]);  
           }  
      }
      //将list转为string。split分隔
      String rtnString = "";//定义返回字符串
      if (list.size()>0) {
      	 for (int j=0; j<list.size(); j++) {  
               if(!checkNull(list.get(j))) {
              	 if(j==0){
              		 rtnString += list.get(j);
              	 }else{
              		 rtnString += split+list.get(j);
              	 }
               }  
           }
		}
	    return rtnString;
	}
  
	//把字符串日期改成时间格式
	public  static Date getTFormatString(String tdate) {
		Date date=null;
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date=df1.parse(tdate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;  
  }
	
	
	/**
	 * 字符串转成Double
	 * 
	 * @param value
	 * @return
	 */
	public static Double StringDouble(String value) {
		DecimalFormat df = new DecimalFormat("0.0");
		if (value == null)
			return null;
		return Double.valueOf(df.format(Double.parseDouble(value)));
	}
	/**
	 * Double保留两位小数
	 * 
	 * @param value
	 * @return
	 */
	public static Double doubleTwo(Double value) {
		DecimalFormat df = new DecimalFormat("0.##");
		if (null != value) {
			value = Double.valueOf(df.format(value));
		}
		return value;
	}
	
	 /**
	  * 随机数
	  * @return
	  */
	 public static  String generateNumber(){
		  String no="";
		  int[] defaultNums = new int[10];
		  for (int i = 0; i < defaultNums.length; i++) {
			  defaultNums[i] = i;
		}
		  Random random=new Random();
		  int[] nums = new int[7];
		  int canBeUsed = 10;
		  for (int i = 0; i < nums.length; i++) {
			int index=random.nextInt(canBeUsed);
			nums[i]=defaultNums[index];
		    swap(index, canBeUsed - 1, defaultNums);
		    canBeUsed--;
		}
		  
		  if(nums.length>0){
			 for (int i = 0; i < nums.length; i++) {
				 no+=nums[i];
			}
		  }
		 return no;
	  }

	 /** 
	* @Title: isNumeric 
	* @Description: TODO(判断字符串是否是数字) 
	* @param @param str
	* @param @return    设定文件 
	* @return boolean    返回类型 
	* @throws 
	*/
	 public static boolean isNumber(String str){  
	        String reg = "^[0-9]+(\\.[0-9]+)?$";  
	        return str.matches(reg);  
	    }  
		 
	    
	 
	  private static final int LENGTH = 7;
	  private static  void swap(int i, int j, int[] nums){
		  int temp = nums[i];
		  nums[i] = nums[j];
		  nums[j] = temp;
	  }
	  
	  public static  String generateNumber2(){
		  String no="";
		 int num[]=new int[7];
		 int c=0;
		 for (int i = 0; i < 7; i++) {
			 num[i] = new Random().nextInt(10);
			 c = num[i];
			 for (int j = 0; j < i; j++) {
				 if (num[j] == c){
					 i--;
					 break;
				 }
			}
		}
		 if (num.length>0){
			 for (int i = 0; i < num.length; i++) {
				 no+=num[i];
			}
		 }
		return no;
		  
	  }
	  /**
		 * 判断字符串大于30截取只取前29个字符,项目名发短信用
		 */
		public static String str(String pro) {
		    String str = "";
	        if(pro != null)
	            str = (pro.length() > 30)?(pro.substring(0, 29)):pro;
		    return str;
		}
	
		//根据时间查询分表后缀（按季度分表1-3月201801  4-6月201802 7-9月201803 10-12月201804）
		public static String getTableSuffix(Date date){
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int year = cal.get(Calendar.YEAR); 
			int month = cal.get(Calendar.MONTH); 
			if(month<3){
				return year+"01";
			}else if(month<6){
				return year+"02";
			}else if(month<9){
				return year+"03";
			}else{
				return year+"04";
			}
		}
		
		/**
		 * 工具方法-判断数组中是否包含某个字符串
		 * @param arr   要判断的数组
		 * @param targetValue	要判断是否包含的字符串
		 * @return
		 */
		public static  boolean  useLoop(String[] arr, String targetValue) {

		    for(String s: arr){
		        if(s.equals(targetValue)){
		            return true;
		        }
		    }
		    return false;
		}
		
		/**
		 * 计算两个日期的相差天数
		 * @param startDate 开始日期
		 * @param endDate	结束日期
		 * @return
		 * @throws ParseException
		 */
		public static int dayBetween(String startDate, String endDate)
			    throws ParseException{
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		    Calendar cal = Calendar.getInstance();
		    cal.setTime(sdf.parse(startDate));
		    long time1 = cal.getTimeInMillis();
		    cal.setTime(sdf.parse(endDate));
		    long time2 = cal.getTimeInMillis();
		    long between_days = (time2 - time1) / 86400000L;
		    
		    return Integer.parseInt(String.valueOf(between_days));
		  }
		
		public static Double toround3(Double d) {
			BigDecimal b = new BigDecimal(d);  
			d = b.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue();
			return d;
		}
		
		 public static Double toround5(Double d)
		  {
		    try {
		    	BigDecimal b = new BigDecimal(d.doubleValue());
			    d = Double.valueOf(b.setScale(5, 4).doubleValue());
			    
			} catch (Exception e) {
				return 0.0;
			}
		    return d;
		  }
		  public static Double avoidNull(Double d){
			return d == null ? 0d : d;
		  }
	public static Integer avoidNull(Integer i){
		return i == null ? 0 : i;
	}

	/**
	 * 当前时间减去某一个时间得到分钟数
	 * @param fenzhong
	 * @return
	 */
	public static long fenzhong(Date fenzhong){
		SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化时间
		String nowtime = d.format(new Date());// 按以上格式 将当前时间转换成字符串
		String testtime = d.format(fenzhong);// 按以上格式 将当前时间转换成字符串
		long result = 0L;
		try {
			result = (d.parse(nowtime).getTime() - d.parse(testtime)
					.getTime()) / 60000;// 当前时间减去测试时间
			// 这个的除以1000得到秒，相应的60000得到分，3600000得到小时
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 时间格式转换--字符串转时间
	 * @param time
	 * @return
	 */
	public static Date stringToDate(String time){
		SimpleDateFormat formatter;
		time = time.replaceAll("t", "");
		int tempPos=time.indexOf("AD") ;
		time=time.trim() ;
		formatter = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss z");
		if(tempPos>-1){
			time=time.substring(0,tempPos)+
					"公元"+time.substring(tempPos+"AD".length());//china
			formatter = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss z");
		}
		tempPos=time.indexOf("-");
		if(tempPos>-1&&(time.indexOf(" ")<0)){
			formatter = new SimpleDateFormat ("yyyyMMddHHmmssZ");
		}
		else if((time.indexOf("/")>-1) &&(time.indexOf(" ")>-1)){
			formatter = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss");
		}
		else if((time.indexOf("-")>-1) &&(time.indexOf(" ")>-1)){
			formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
		}
		if((time.indexOf("/")>-1) &&(time.indexOf("AM")>-1) ||(time.indexOf("PM")>-1)){
			DateFormat formatFrom = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss aa", Locale.ENGLISH);
			formatter = (SimpleDateFormat) formatFrom;
		}
		if((time.indexOf("-")>-1) &&(time.indexOf("AM")>-1) ||(time.indexOf("PM")>-1)){
			DateFormat formatFrom = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss aa", Locale.ENGLISH);
			formatter = (SimpleDateFormat) formatFrom;
		}
		if((time.indexOf("/")>-1) &&(time.indexOf("am")>-1) ||(time.indexOf("pm")>-1)){
			DateFormat formatFrom = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss aa", Locale.ENGLISH);
			formatter = (SimpleDateFormat) formatFrom;
		}
		if((time.indexOf("-")>-1) &&(time.indexOf("am")>-1) ||(time.indexOf("pm")>-1)){
			DateFormat formatFrom = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss aa", Locale.ENGLISH);
			formatter = (SimpleDateFormat) formatFrom;
		}
		ParsePosition pos = new ParsePosition(0);
		Date ctime = formatter.parse(time, pos);

		return ctime;
	}

	// 封装返回信息
	public static String rtnMsg(String status, String msg) {
		Map<String, Object> chartData = new HashMap<String, Object>();
		//状态 0失败  1成功
		chartData.put("status", status);
		//信息
		chartData.put("msg", msg);
		String dataJson = JsonUtils.toJson(chartData);
		return dataJson;

	}
	
	// 封装返回信息
	public static String rtnMsgCar(String code, String msg) {
		Map<String, Object> chartData = new HashMap<String, Object>();
		//状态 0失败  1成功
		chartData.put("code", code);
		//信息
		chartData.put("msg", msg);
		String dataJson = JsonUtils.toJson(chartData);
		return dataJson;
		
	}
	//根据时间查询分表后缀（按季度分表1-3月201801  4-6月201802 7-9月201803 10-12月201804）
	public static String getTableFolname(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int year = cal.get(Calendar.YEAR); 
		int month = cal.get(Calendar.MONTH); 
		System.out.println("month="+month);
		if(month<3){
			return year+"01";
		}else if(month<6){
			return year+"02";
		}else if(month<9){
			return year+"03";
		}else{
			return year+"04";
		}
	}

	public static BigDecimal checkBigDecimal(Double data)
	{
		BigDecimal rtn = new BigDecimal(0.0);
		if (!checkNull(data)) {
			rtn =  new BigDecimal(data);
		}
		return rtn;
	}

	public static String filterStrNull(String str){
		return StringUtils.isEmpty(str)?"":str;
	}

}